package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.file.template.MinIOTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApArticleFreemarkerServiceImpl implements ApArticleFreemarkerService {

    @Resource
    private MinIOTemplate minIOTemplate;

    @Resource
    private Configuration configuration;

    /**
     *发布文章内容
     * @param id 文章id
     * @param content 文章内容数据
     * @return
     */
    @Override
    public String buildArticle2MinIo(long id, String content) {

        //参数校验
        if(StringUtils.isEmpty(content)){
            return null;
        }

        try {
            //生成数据模型
            Map<String,Object> modelMap=new HashMap<>();
            modelMap.put("content",JSON.parseArray(content));

            //加载模板
            Template template = configuration.getTemplate("article.ftl");
            //生成页面
            StringWriter writer = new StringWriter();
            template.process(modelMap,writer);

            //将静态页面上传到MinIO
            InputStream is=new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOTemplate.uploadHtmlFile("", id + ".html", is);
            log.info("上传的静态页面地址为:{}",url);

            return url;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成静态页面失败,文章的id:{},错误原因:{}",id,e.getMessage());
            return null;
        }
    }
}
